<?php
/**
 * 商品API逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\api\logic;

use app\common\logic\Product as CommonProduct;
use app\common\logic\Category as CommonCategory;
use app\common\logic\Price as CommonPrice;

class Product extends ApiBase
{
    
    public static $commonProductLogic = null;
    public static $commonCategoryLogic = null;
    public static $commonPriceLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonProductLogic) && static::$commonProductLogic = new CommonProduct();
        empty(static::$commonCategoryLogic) && static::$commonCategoryLogic = new CommonCategory();
        empty(static::$commonPriceLogic) && static::$commonPriceLogic = new CommonPrice();
    }

    /**
     * 获取首页推荐商品
     */
    public function getHomeRecommend($data = [])
    {
        // 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['category_id', 'limit', 'type'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 调用common层获取首页推荐
        $result = static::$commonProductLogic->getHomeRecommend($queryData);
        
        return $result;
    }
    
    /**
     * 获取产品列表
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getProductList($data = [])
    {
        $where = static::$commonProductLogic->getWhere($data);

        $sortBy = $data['sort_by'] ?? 'id';
        $sortOrder = $data['sort_order'] ?? 'desc';
        $order = 's.' . $sortBy . ' ' . $sortOrder;

        $list = static::$commonProductLogic->getProductList($where, 's.*', $order);

        return $list;
    }
    
    /**
     * 获取商品详情
     */
    public function getProductDetail($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            if ($userData) {
                $data['user_id'] = $userData['user_id'];
            }
        }
        
        // 2. 检查是否为市场行情信息请求
        $isMarketInfoRequest = isset($data['market_info_mode']) && $data['market_info_mode'] == 1;
        
        if ($isMarketInfoRequest) {
            // 市场行情信息模式：过滤掉API相关字段，只保留数据库查询相关字段
            $queryData = [];
            $allowedFields = ['id', 'product_id', 'user_id'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $queryData[$field] = $data[$field];
                }
            }
            
            // 调用Market的getMarketInfo逻辑
            $marketWhere = $queryData;
            $marketWhere['status'] = 1;
            
            $result = $this->modelProduct->getInfo($marketWhere, true);
        } else {
            // 原有商品详情模式
            // 验证参数
            if (!$this->validateProduct->scene('detail')->check($data)) {
                return [RESULT_ERROR, $this->validateProduct->getError()];
            }
            
            // 过滤掉API相关字段，只保留数据库查询相关字段
            $queryData = [];
            $allowedFields = ['id', 'product_id'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $queryData[$field] = $data[$field];
                }
            }
            
            // 调用common层获取商品详情
            $result = static::$commonProductLogic->getProductDetail($queryData);
        }
        
        return $result;
    }
    
    /**
     * 获取商品历史行情
     */
    public function getProductHistory($data = [])
    {
        // 验证参数
        if (!$this->validateProduct->scene('history')->check($data)) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        // 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['product_id', 'days'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 调用common层获取历史行情
        $result = static::$commonProductLogic->getProductHistory($queryData);
        
        return $result;
    }
    
    /**
     * 搜索商品
     */
    public function searchProduct($data = [])
    {
        // 验证参数
        if (!$this->validateProduct->scene('search')->check($data)) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        // 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['keyword', 'category_id', 'page', 'limit'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 调用common层搜索商品
        $result = static::$commonProductLogic->searchProduct($queryData);
        
        return $result;
    }
    
    /**
     * 获取商品分类
     */
    public function getProductCategories($data = [])
    {
        // 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['parent_id', 'level'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 调用common层Category逻辑获取分类
        $result = static::$commonCategoryLogic->getCategoryList($queryData);
        
        return $result;
    }
    
    /**
     * 添加浏览历史
     */
    public function addViewHistory($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        // 2. 验证参数
        if (!$this->validateProduct->scene('addViewHistory')->check($data)) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        // 3. 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['user_id', 'product_id'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 4. 调用common层添加浏览历史
        $result = static::$commonProductLogic->addViewHistory($queryData);
        
        return $result;
    }
    
    /**
     * 获取用户浏览历史
     */
    public function getUserViewHistory($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        // 2. 验证参数
        if (!$this->validateProduct->scene('getUserViewHistory')->check($data)) {
            return [RESULT_ERROR, $this->validateProduct->getError()];
        }
        
        // 3. 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['user_id', 'page', 'limit'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 4. 调用common层获取用户浏览历史
        $result = static::$commonProductLogic->getUserViewHistory($queryData);
        
        return $result;
    }

    /**
     * 获取热门商品
     */
    public function getHotProducts($data = [])
    {
        $where = [
            's.status' => 1,
        ];

        $order = 's.view_count DESC, s.id DESC';

        $list = static::$commonProductLogic->getProductList($where, 's.*', $order, 40);

        return $list;
    }

    /**
     * 商品详情页综合数据
     * 包含：商品基本信息、价格历史、关注状态、相关推荐、统计数据
     */
    public function getDetailPage($data = [])
    {
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        $productId = isset($data['product_id']) ? intval($data['product_id']) : 0;
        if ($productId <= 0) {
            return [API_CODE_NAME => -1, API_MSG_NAME => '商品ID不能为空'];
        }

        $userId = isset($data['user_id']) ? intval($data['user_id']) : 0;

        $product = static::$commonProductLogic->getProductInfo(['id' => $productId]);
        if (empty($product)) {
            return [API_CODE_NAME => -1, API_MSG_NAME => '商品不存在或已下架'];
        }

        $images = [];
        if (!empty($product['img_ids'])) {
            $images = $this->modelPicture->getList([
                'id' => ['in', explode(',', $product['img_ids'])],
                'status' => 1
            ], 'path', 'id', false);
        }

        $historyRes = static::$commonPriceLogic->getPriceHistory(['product_id' => $productId, 'days' => 10]);
        $historyList = ($historyRes && is_array($historyRes) && $historyRes[0] == RESULT_SUCCESS) ? $historyRes[2] : [];

        $trendRes = static::$commonPriceLogic->getPriceTrend(['product_id' => $productId, 'period' => '30d']);
        $trendData = ($trendRes && is_array($trendRes) && $trendRes[0] == RESULT_SUCCESS) ? $trendRes[2] : [];

        $trend = 'flat';
        if (!empty($trendData) && count($trendData) >= 2) {
            $firstPrice = floatval($trendData[0]['price']);
            $lastPrice = floatval($trendData[count($trendData) - 1]['price']);
            $trend = $lastPrice > $firstPrice ? 'up' : ($lastPrice < $firstPrice ? 'down' : 'flat');
        } elseif (isset($product['change_rate'])) {
            $trend = $product['change_rate'] > 0 ? 'up' : ($product['change_rate'] < 0 ? 'down' : 'flat');
        }

        $isFollowed = false;
        if ($userId > 0) {
            $followInfo = $this->modelUserFollow->getInfo([
                'user_id' => $userId,
                'product_id' => $productId,
                'status' => 1
            ]);
            $isFollowed = !empty($followInfo);
        }

        $product['images'] = $images;
        $product['price_trend'] = $trend;

        $result = [
            'product' => $product,
            'price_history' => [
                'chart_data' => $trendData,
                'list' => $historyList
            ],
            'is_followed' => $isFollowed
        ];

        return [API_CODE_NAME => 0, API_MSG_NAME => '获取成功', 'data' => $result];
    }

    /**
     * 商品列表页综合数据
     * 包含：商品列表、分类信息、筛选条件、热门推荐
     */
    public function getListPage($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        // 2. 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['category_id', 'page', 'limit', 'sort', 'user_id'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 3. 调用common层获取列表页数据
        $result = static::$commonProductLogic->getListPage($queryData);
        
        return $result;
    }

    /**
     * 商品搜索页综合数据
     * 包含：搜索结果、热门搜索、搜索建议、相关分类
     */
    public function getSearchPage($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        
        // 2. 验证参数
        if (!isset($data['keyword']) || empty($data['keyword'])) {
            return [RESULT_ERROR, '搜索关键词不能为空'];
        }
        
        // 3. 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['keyword', 'category_id', 'page', 'limit', 'sort', 'user_id'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 4. 调用common层获取搜索页数据
        $result = static::$commonProductLogic->getSearchPage($queryData);
        
        return $result;
    }



}